package com.example.java_chatroom.api;

import com.example.java_chatroom.model.User;
import com.example.java_chatroom.model.UserMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.messaging.rsocket.annotation.ConnectMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@Slf4j
public class UserApi {
    @Resource
    public UserMapper userMapper;

    //登录
    @RequestMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest req) {
        //先在数据库中查找User对象
        //如果能找到 查看密码是否匹配
        User user = userMapper.selectByName(username);
        if (user == null || !user.getPassword().equals(password)) {
            log.info("登录失败 username:", username, "password:", password);
            return new User();
        }
        //如果能找到 则登录成功 保存session
        HttpSession session = req.getSession();
        session.setAttribute("user", user);
        //在返回之前把password置空
        user.setPassword(null);
        return user;
    }


    //注册
    @RequestMapping("/register")
    @ResponseBody
    public Object register(String username, String password) {
        User user = new User();
        try {
            user.setUsername(username);
            user.setPassword(password);
            int ret = userMapper.insert(user);
            log.info("注册成功 ret:", ret);
            user.setPassword("");
        } catch (DuplicateKeyException e) {
            //如果 insert 抛出异常 就是名字重复 则注册失败
            user = new User();
        }
        return user;
    }

    @RequestMapping("/getInfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest req){
        //1. 从session中获取user
        HttpSession session=req.getSession();
        if(session==null){
            log.info("session is null");
            return new User();
        }
        //2. 从session中获取user
        User user=(User)session.getAttribute("user");
        if(user==null){
            log.info("user is null");
            return new User();
        }
        user.setPassword(null);
        return user;
    }



}
//    User user=new User();
//        try {
//                user.setUsername(username);
//                user.setPassword(password);
//                int ret= userMapper.insert(user);
//                log.info("注册成功 ret:",ret);
//                //DuplicateKeyException 异常表示用户名重复 注册失败
//                } catch (DuplicateKeyException e) {
//                //如果 insert 抛出异常 就是名字重复 则注册失败
//                user=new User();
//                }
//                return user;